package cn.iocoder.yudao.module.strategy.service.strategy;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.strategy.controller.admin.strategy.vo.*;
import cn.iocoder.yudao.module.strategy.convert.strategy.StrategyConvert;
import cn.iocoder.yudao.module.strategy.dal.dataobject.strategy.StrategyDO;
import cn.iocoder.yudao.module.strategy.dal.mysql.strategy.StrategyMapper;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.strategy.enums.ErrorCodeConstants.NOT_EXISTS;

/**
 * 企业战略（短期、长期） Service 实现类
 *
 * @author huangjunwei
 */
@Service
@Validated
@Slf4j
public class StrategyServiceImpl implements StrategyService {

    @Resource
    private StrategyMapper strategyMapper;

    @Resource
    private DeptService deptService;

    @Resource
    private AdminUserService adminUserService;


    @Override
    public Long create(StrategyCreateReqVO createReqVO) {
        // 插入
        StrategyDO strategyDO = StrategyConvert.INSTANCE.convert(createReqVO);
        strategyMapper.insert(strategyDO);
        // 返回
        return strategyDO.getId();
    }

    @Override
    public void update(StrategyUpdateReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        StrategyDO updateObj = StrategyConvert.INSTANCE.convert(updateReqVO);
        strategyMapper.updateById(updateObj);
    }

    @Override
    public void delete(Long id) {
        // 校验存在
        validateExists(id);
        // 删除
        strategyMapper.deleteById(id);
    }

    private void validateExists(Long id) {
        if (strategyMapper.selectById(id) == null) {
            throw exception(NOT_EXISTS);
        }
    }

    @Override
    public StrategyDO get(Long id) {
        return strategyMapper.selectById(id);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public StrategyRespVO getStrategyRespVO(Long id) {
        StrategyDO strategyDO = this.get(id);
        StrategyRespVO strategyRespVO = StrategyConvert.INSTANCE.convert(strategyDO);
        this.rebuildStrategyRespVO(strategyRespVO);

        return strategyRespVO;
    }

    /**
     * 重新构建trategyRespVO对象
     */
    private void rebuildStrategyRespVO(StrategyRespVO strategyRespVO) {
        //组织
        DeptDO dept = deptService.getDept(strategyRespVO.getOrganizationId());
        if (dept != null) {
            strategyRespVO.setOrganizationName(dept.getName());
        }
        //创建者姓名
        if (StringUtils.isNotBlank(strategyRespVO.getCreator())) {
            AdminUserDO adminUserDO = adminUserService.getUser(Long.valueOf(strategyRespVO.getCreator()));
            if (adminUserDO != null) {
                strategyRespVO.setCreatorName(adminUserDO.getNickname());
            }
        }
        //更新者姓名
        if (StringUtils.isNotBlank(strategyRespVO.getUpdater())) {
            AdminUserDO adminUserDO = adminUserService.getUser(Long.valueOf(strategyRespVO.getUpdater()));
            if (adminUserDO != null) {
                strategyRespVO.setUpdaterName(adminUserDO.getNickname());
            }
        }
        //决策者姓名
        AdminUserDO adminUserDO = adminUserService.getUser(strategyRespVO.getDecisionUser());
        if (adminUserDO != null) {
            strategyRespVO.setDecisionUserName(adminUserDO.getNickname());
        }
    }

    @Override
    public List<StrategyDO> getList(Collection<Long> ids) {
        return strategyMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<StrategyDO> getPage(StrategyPageReqVO pageReqVO) {
        return strategyMapper.selectPage(pageReqVO);
    }

    /**
     * 获得企业战略（短期、长期）分页
     *
     * @param pageReqVO 分页查询
     * @return 企业战略（短期、长期）分页
     */
    @Override
    public PageResult<StrategyRespVO> getPageStrategyRespVO(StrategyPageReqVO pageReqVO) {
        PageResult<StrategyDO> strategyDOPageResult = this.getPage(pageReqVO);

        PageResult<StrategyRespVO> strategyRespVOPageResult = StrategyConvert.INSTANCE.convertPage(strategyDOPageResult);
        if (strategyRespVOPageResult != null && !CollectionUtils.isEmpty(strategyRespVOPageResult.getList())) {
            List<StrategyRespVO> strategyRespVOList = strategyRespVOPageResult.getList();
            this.rebuildStrategyRespVOList(strategyRespVOList);
        }
        return strategyRespVOPageResult;
    }

    private void rebuildStrategyRespVOList(List<StrategyRespVO> strategyRespVOList) {
        //组织
        Set<Long> deptIdSet = strategyRespVOList.stream()
                .filter(Objects::nonNull)
                .map(StrategyBaseVO::getOrganizationId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        //查组织
        List<DeptDO> deptDOList = deptService.getDeptList(deptIdSet);
        Map<Long, DeptDO> deptDOMap = new HashMap<>();
        deptDOList.forEach(item -> {
            deptDOMap.put(item.getId(), item);
        });
        //设置组织
        for (StrategyRespVO strategyRespVO : strategyRespVOList) {
            if (deptDOMap.get(strategyRespVO.getOrganizationId()) != null) {
                strategyRespVO.setOrganizationName(deptDOMap.get(strategyRespVO.getOrganizationId()).getName());
            }
        }

        //创建者+更新者+决策者
        Set<String> userIdStringSet = strategyRespVOList.stream()
                .filter(Objects::nonNull)
                .flatMap(item -> {
                    return Stream.of(item.getCreator(), item.getUpdater(), String.valueOf(item.getDecisionUser()));
                })
                .filter(id -> StringUtils.isNotBlank(id))
                .collect(Collectors.toSet());
        //将Set<String>转换为Set<Long>
        Set<Long> userIdLongSet = userIdStringSet.stream()
                .map(userIdString -> {
                    try {
                        return Long.parseLong(userIdString);
                    } catch (Exception e) {
                        log.error("用户相关数据异常，strategyRespVOList：" + JSON.toJSONString(strategyRespVOList), e);
                        return null;
                    }
                })
                .filter(Objects::nonNull) // 过滤掉空的
                .collect(Collectors.toSet());
        //查用户
        List<AdminUserDO> adminUserDOList = adminUserService.getUserList(userIdLongSet);
        Map<Long, AdminUserDO> adminUserDOMap = new HashMap<>();
        adminUserDOList.forEach(item -> {
            adminUserDOMap.put(item.getId(), item);
        });
        //设置用户姓名
        for (StrategyRespVO strategyRespVO : strategyRespVOList) {
            AdminUserDO adminUserDOFromMap = null;
            //创建者
            adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyRespVO.getCreator()));
            if (adminUserDOFromMap != null) {
                strategyRespVO.setCreatorName(adminUserDOFromMap.getNickname());
            }
            //更新者
            adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyRespVO.getUpdater()));
            if (adminUserDOFromMap != null) {
                strategyRespVO.setUpdaterName(adminUserDOFromMap.getNickname());
            }
            //决策者
            adminUserDOFromMap = adminUserDOMap.get(strategyRespVO.getDecisionUser());
            if (adminUserDOFromMap != null) {
                strategyRespVO.setDecisionUserName(adminUserDOFromMap.getNickname());
            }
        }
    }

    @Override
    public List<StrategyDO> getList(StrategyExportReqVO exportReqVO) {
        return strategyMapper.selectList(exportReqVO);
    }

}
